package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.LinkListPojo;
import com.xbongbong.paas.help.CloudCodeHelp;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.FormDataFormExplainHelper;
import com.xbongbong.paas.help.LinkListHelp;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.DetailTabPojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.detailtab.dto.DetailTabSettingGetDTO;
import com.xbongbong.pro.detailtab.pojo.TabConfigPojo;
import com.xbongbong.pro.detailtab.vo.DetailTabSettingGetVO;
import com.xbongbong.pro.domain.entity.DetailTabConfigEntity;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.BusinessDetailTabEnum;
import com.xbongbong.saas.enums.DetailTabEnum;
import com.xbongbong.saas.enums.PaasDetailTabEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.DetailTabConfigModel;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.util.ContractCompareUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2022/11/19 16:49
 */
@Service("ProDetailTabConfigService")
public class ProDetailTabConfigService {
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private LinkListHelp linkListHelp;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private DetailTabConfigModel detailTabConfigModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private FormDataFormExplainHelper formDataFormExplainHelper;
    @Resource
    private CloudCodeHelp cloudCodeHelp;
    @Resource
    private ContractCompareUtil contractCompareUtil;

    public DetailTabSettingGetVO getDetailTabSet(DetailTabSettingGetDTO detailTabSettingGetDTO) throws XbbException {
        DetailTabSettingGetVO detailTabSettingGetVO = new DetailTabSettingGetVO();
        UserVO loginUser = detailTabSettingGetDTO.getLoginUser();
        Integer saasMark = detailTabSettingGetDTO.getSaasMark();
        String corpid = detailTabSettingGetDTO.getCorpid();
        String userId = detailTabSettingGetDTO.getUserId();
        List<TabConfigPojo> tabConfigPojos = new ArrayList<>();
        PaasFormExplainEntity explainEntity = new PaasFormExplainEntity();
        PaasFormEntity paasFormEntity = new PaasFormEntity();
        Integer distributorMark = detailTabSettingGetDTO.getDistributorMark();
        if (Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode())) {
            detailTabSettingGetDTO.setBusinessType(XbbRefTypeEnum.transferBusinessType4Distributor(detailTabSettingGetDTO.getBusinessType(), distributorMark));
        }
        Integer businessType = detailTabSettingGetDTO.getBusinessType();
        if (Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())) {
            WorkOrderFormEntity workOrderFormEntity = workOrderFormModel.getByKey(detailTabSettingGetDTO.getFormId(), corpid);
            if (Objects.isNull(workOrderFormEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            BeanUtil.copyProperties(workOrderFormEntity, paasFormEntity);
            WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByFormId(detailTabSettingGetDTO.getFormId(), corpid);
            if (Objects.isNull(workOrderExplainEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            BeanUtil.copyProperties(workOrderExplainEntity, explainEntity);
        } else {
            paasFormEntity = paasFormModel.getByKey(detailTabSettingGetDTO.getFormId(), corpid);
            if (Objects.isNull(paasFormEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            explainEntity = paasFormExplainModel.getByFormId(detailTabSettingGetDTO.getFormId(), corpid);
        }
        if (Objects.isNull(explainEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        List<FieldAttrEntity> fieldAttrEntityList = JSONArray.parseArray(explainEntity.getExplains(), FieldAttrEntity.class);
        Map<String, FieldAttrEntity> subFormMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<String> existAttrList = new ArrayList<>();
        for (FieldAttrEntity item : fieldAttrEntityList) {
            if (FieldTypeEnum.SUB_FORM.getType().equals(item.getFieldType()) || FieldTypeEnum.SELECT_PRODUCT.getType().equals(item.getFieldType())) {
                subFormMap.put(item.getAttr(), item);
                existAttrList.add(item.getAttr());
            }
        }
        // 获取关联列表
        List<LinkListPojo> associationList = JSONArray.parseArray(paasFormEntity.getAssociationList(), LinkListPojo.class);
        if (Objects.isNull(associationList)) {
            associationList = new ArrayList<>();
        }
        // 获取下关联列表
        linkListHelp.getLinkList(associationList, corpid);
        List<DetailTabPojo> detailTabList = new ArrayList<>();
        // 返回当前用户权限下的tab
        linkListHelp.getLinkListTab(associationList, detailTabList, loginUser);
        Map<String, DetailTabPojo> detailTabMap = new HashMap<>(detailTabList.size());
        detailTabList.forEach(item->{
            detailTabMap.put(item.getAttr(), item);
            existAttrList.add(item.getAttr());
        });

        DetailTabConfigEntity tabConfigEntity = detailTabConfigModel.getEntityByBusinessTypeAndFormId(corpid, userId, businessType, detailTabSettingGetDTO.getFormId());
        TabConfigPojo tabConfigPojo;
        if (SaasMarkEnum.SAAS.getCode().equals(saasMark)) {
            tabConfigPojos = getSaasTabConfig(detailTabSettingGetDTO, existAttrList, tabConfigEntity, subFormMap, detailTabMap, fieldAttrEntityList);
        } else {
            // paas
            Integer sort = 1;
            if (Objects.nonNull(tabConfigEntity)) {
                tabConfigPojos = JSONArray.parseArray(tabConfigEntity.getTabConfig(), TabConfigPojo.class);
                Map<String, TabConfigPojo> configPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                tabConfigPojos.forEach(configPojo -> configPojoMap.put(configPojo.getAttr(), configPojo));
                for (PaasDetailTabEnum paasDetailTabEnum : PaasDetailTabEnum.values()) {
                    String key = paasDetailTabEnum.getAnEnum().getKey();
                    if (!configPojoMap.containsKey(key)) {
                        tabConfigPojo = new TabConfigPojo(key, paasDetailTabEnum.getAnEnum().getName(), key, BasicConstant.IS_USE, sort++, "");
                        tabConfigPojos.add(tabConfigPojo);
                    }
                    existAttrList.add(key);
                }
                tabConfigPojos.removeIf(tab -> !existAttrList.contains(tab.getAttr()));
                sort = tabConfigPojos.size() + 1;
                setLastAddSubFormSort(tabConfigPojos, subFormMap, configPojoMap, sort);
                setLastLinkListSort(tabConfigPojos, detailTabMap, configPojoMap, sort);
            } else {
                List<PaasDetailTabEnum> paasDetailTabEnums = PaasDetailTabEnum.getWebTabList();
                boolean openWorkFlow = commonHelp.isOpenWorkFlow(detailTabSettingGetDTO.getCorpid());
                List<Object> pojoList = new ArrayList<>();
                //默认情况，审批的tab放最后
                paasDetailTabEnums.removeIf(v -> Objects.equals(v.getAnEnum(), DetailTabEnum.APPROVAL_RECORDS));
                if(openWorkFlow){
                    pojoList.add(PaasDetailTabEnum.APPROVAL_RECORDS);
                }

                for (PaasDetailTabEnum paasDetailTabEnum : paasDetailTabEnums) {
                    tabConfigPojo = new TabConfigPojo();
                    BeanUtil.copyProperties(paasDetailTabEnum.getAnEnum(), tabConfigPojo);
                    tabConfigPojo.setAttr(paasDetailTabEnum.getAnEnum().getKey());
                    tabConfigPojo.setEnable(BasicConstant.IS_USE);
                    tabConfigPojo.setSort(sort++);
                    if (Objects.equals(paasDetailTabEnum.getAnEnum().getKey(),PaasDetailTabEnum.STAGE_HISTORY.getAnEnum().getKey())){
                        tabConfigPojo.setSpecialMemo("仅当拥有阶段推进器权限时展示");
                    }
                    tabConfigPojos.add(tabConfigPojo);

                }
                setSubFormTabSort(tabConfigPojos, subFormMap, sort, pojoList);
                setLastLinkListSort(tabConfigPojos, detailTabMap, new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY), sort);
            }
        }
        // 去除无权限或者已被删除的关联列表
        deleteLinkList(tabConfigPojos, detailTabMap);
        cloudCodeHelp.setCloudCodeTabConfig(corpid, detailTabSettingGetDTO.getLoginUser().getDynamicPermSet(), detailTabSettingGetDTO.getAppId(), detailTabSettingGetDTO.getFormId(),
                detailTabSettingGetDTO.getBusinessType(), tabConfigEntity, tabConfigPojos);
        //老数据阶段工作修改为阶段历史
        for (TabConfigPojo temp : tabConfigPojos) {
            if (Objects.equals(temp.getAttr(), BusinessDetailTabEnum.CUSTOMER_CUSTOMER_STAGE.getAnEnum().getKey())) {
                temp.setName(BusinessDetailTabEnum.CUSTOMER_CUSTOMER_STAGE.getAnEnum().getName());
                break;
            }
        }
        detailTabSettingGetVO.setTabConfig(tabConfigPojos);
        return detailTabSettingGetVO;
    }

    protected List<TabConfigPojo> getSaasTabConfig(DetailTabSettingGetDTO detailTabSettingGetDTO, List<String> existAttrList, DetailTabConfigEntity tabConfigEntity, Map<String, FieldAttrEntity> subFormMap,  Map<String, DetailTabPojo> detailTabMap, List<FieldAttrEntity> fieldAttrEntityList) throws XbbException {
        boolean quotationShow = true;
        Integer businessType = detailTabSettingGetDTO.getBusinessType();
        String corpid = detailTabSettingGetDTO.getCorpid();
        if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())) {
            PaasMenuEntity customerQuotation = paasMenuModel.getByAlias(XbbRefTypeEnum.QUOTATION.getAlias(), null, corpid);
            if (customerQuotation == null || Objects.equals(customerQuotation.getEnable(), BasicConstant.ZERO)) {
                // 报价单菜单不开启，客户和机会详情中的报价单tab不展示
                quotationShow = false;
            }
        }
        boolean parentCustomerShow = true;
        if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
            parentCustomerShow = setParentCustomerShow(detailTabSettingGetDTO, fieldAttrEntityList);
        }
        UserVO loginUser = detailTabSettingGetDTO.getLoginUser();
        Integer distributorMark = detailTabSettingGetDTO.getDistributorMark();
        // saas详情tab
        List<BusinessDetailTabEnum> tabEnumList = BusinessDetailTabEnum.getByBusinessTypeAndPermission(businessType, loginUser.getPermSet());
        boolean openWorkFlow = commonHelp.isOpenWorkFlow(detailTabSettingGetDTO.getCorpid());
        if(!openWorkFlow){
            tabEnumList.removeIf(v -> Objects.equals(v.getAnEnum(), DetailTabEnum.APPROVAL_RECORDS));
        }
        List<String> paasAlias = new ArrayList<>();
        tabEnumList.forEach(item ->{
            if (item.getFormBusinessType() != 0){
                paasAlias.add(XbbRefTypeEnum.getByCode(item.getFormBusinessType()).getAlias());
            }
        });
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", detailTabSettingGetDTO.getCorpid());
        param.put("aliasIn", paasAlias);
        param.put("del", DelEnum.NORMAL.getDel());
        List<PaasMenuEntity> paasMenuEntitys = paasMenuModel.findEntitys(param);
        HashMap<Integer,String> paasBusinessTypeToName = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Integer> customerOrCcontactCode = Arrays.asList(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), XbbRefTypeEnum.CONTACT.getCode());
        paasMenuEntitys.forEach(item -> {
            // 客户＆经销商客户　联系人＆经销商联系人 businessType值相同，根据distributorMark判断
            if (customerOrCcontactCode.contains(XbbRefTypeEnum.getByAlias(item.getAlias()).getCode()) && !Objects.equals(item.getDistributorMark(), distributorMark)) {
                return;
            }
            paasBusinessTypeToName.put(XbbRefTypeEnum.getByAlias(item.getAlias()).getCode(),item.getName());
        });
        tabEnumList.forEach(tab -> existAttrList.add(tab.getAnEnum().getKey()));
        if (Objects.nonNull(tabConfigEntity)) {
            List<TabConfigPojo> tabConfigPojos = JSONArray.parseArray(tabConfigEntity.getTabConfig(), TabConfigPojo.class);
            Map<String, TabConfigPojo> configPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            tabConfigPojos.forEach(configPojo -> {
                String attr = configPojo.getAttr();
                if (subFormMap.containsKey(attr)) {
                    String attrName = subFormMap.get(attr).getAttrName();
                    if (Objects.nonNull(attrName)) {
                        configPojo.setName(attrName);
                    }
                }
                configPojoMap.put(attr, configPojo);
            });
            Integer sort = tabConfigPojos.size() + 1;
            // 保存修改枚举中修改过的菜单值
            Map<String,String> saasAliasToName = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            TabConfigPojo tabConfigPojo;
            for (BusinessDetailTabEnum detailTabEnum : tabEnumList) {
                if (configPojoMap.containsKey(detailTabEnum.getAnEnum().getKey())){
                    if (detailTabEnum.getFormBusinessType() != 0
                            && Objects.nonNull(paasBusinessTypeToName.get(detailTabEnum.getFormBusinessType()))
                            && !Objects.equals(paasBusinessTypeToName.get(detailTabEnum.getFormBusinessType()), XbbRefTypeEnum.getByCode(detailTabEnum.getFormBusinessType()).getName())) {
                        saasAliasToName.put(detailTabEnum.getAnEnum().getKey(), paasBusinessTypeToName.get(detailTabEnum.getFormBusinessType()));
                    }
                }
                if (!configPojoMap.containsKey(detailTabEnum.getAnEnum().getKey())) {
                    tabConfigPojo = new TabConfigPojo();
                    BeanUtil.copyProperties(detailTabEnum.getAnEnum(), tabConfigPojo);
                    tabConfigPojo.setAttr(detailTabEnum.getAnEnum().getKey());
                    tabConfigPojo.setEnable(BasicConstant.IS_USE);
                    tabConfigPojo.setSpecialMemo(detailTabEnum.getSpecialMemo());
                    tabConfigPojo.setSort(sort++);
                    tabConfigPojos.add(tabConfigPojo);
                }
            }
            Boolean isShowCompareTab = contractCompareUtil.showCompareTab(corpid, loginUser.getPermSet(), detailTabSettingGetDTO.getUserId());
            tabConfigPojos.removeIf(tab -> (Objects.equals(tab.getAttr(), XbbRefTypeEnum.CONTRACT_COMPARE.getAlias()) && !isShowCompareTab));
            tabConfigPojos.removeIf(tab -> !existAttrList.contains(tab.getAttr()));
            if (!quotationShow) {
                tabConfigPojos.removeIf(item -> (Objects.equals(item.getAttr(), DetailTabEnum.CUSTOMER_QUOTATION.getKey()) || Objects.equals(item.getAttr(), DetailTabEnum.OPPORTUNITY_QUOTATION.getKey())));
            }
            if (!parentCustomerShow) {
                tabConfigPojos.removeIf(item -> (Objects.equals(item.getAttr(), DetailTabEnum.PARENT_AND_CHILD.getKey())));
            }
            setLastAddSubFormSort(tabConfigPojos, subFormMap, configPojoMap, sort);
            setLastLinkListSort(tabConfigPojos, detailTabMap, configPojoMap, sort);
            tabConfigPojos.removeIf(item -> Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(item.getAttr(), ProductEnum.STOCK_NOTIFY.getAttr()));
            tabConfigPojos.forEach(item -> {
                if (StringUtil.isNotEmpty(saasAliasToName.get(item.getAttr()))){
                    item.setName(saasAliasToName.get(item.getAttr()));
                }
            });
            return tabConfigPojos;
        } else {
            //审批相关的tab，默认放在最后面
            //过滤下是否有审批tab
            boolean hasApproval = false;
            List<Object> pojoList = new ArrayList<>();
            for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                if(Objects.equals(tabEnum.getAnEnum(),DetailTabEnum.APPROVAL_RECORDS)){
                    hasApproval = true;
                    pojoList.add(tabEnum);
                }
                if(Objects.equals(tabEnum, DetailTabEnum.APPROVAL_PROCESS.getKey()) || Objects.equals(tabEnum, DetailTabEnum.APPROVAL_HISTORY.getKey())){
                    hasApproval = true;
                    pojoList.add(tabEnum);
                }
            }
            if(hasApproval){
                tabEnumList.removeIf(pojoList :: contains);
            }

            Integer sort = 1;
            TabConfigPojo tabConfigPojo;
            List<TabConfigPojo> tabConfigPojos = new ArrayList<>();
            for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                if (!quotationShow && (Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_QUOTATTIO) || Objects.equals(tabEnum, BusinessDetailTabEnum.SALES_OPPORTUNITY_QUOTATION))) {
                    continue;
                }
                if (!parentCustomerShow && (Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_PARENT_AND_CHILD))) {
                    continue;
                }
                if (Objects.equals(tabEnum.getAnEnum().getKey(), DetailTabEnum.CONTRACT_COMPARE.getKey()) && !contractCompareUtil.showCompareTab(corpid, loginUser.getPermSet(), detailTabSettingGetDTO.getUserId())) {
                    continue;
                }
                tabConfigPojo = new TabConfigPojo();
                BeanUtil.copyProperties(tabEnum.getAnEnum(), tabConfigPojo);
                changeDefaultName(tabConfigPojo, paasBusinessTypeToName, tabEnum.getFormBusinessType());
                tabConfigPojo.setAttr(tabEnum.getAnEnum().getKey());
                tabConfigPojo.setEnable(BasicConstant.IS_USE);
                tabConfigPojo.setSort(sort++);
                tabConfigPojo.setSpecialMemo(tabEnum.getSpecialMemo());
                tabConfigPojos.add(tabConfigPojo);
            }
            setSubFormTabSort(tabConfigPojos, subFormMap, sort, pojoList);
            tabConfigPojos.removeIf(item -> Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(item.getAttr(), ProductEnum.STOCK_NOTIFY.getAttr()));
            setLastLinkListSort(tabConfigPojos, detailTabMap, new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY), sort);
            return tabConfigPojos;
        }
    }

    protected void changeDefaultName(TabConfigPojo tabConfigPojo, Map<Integer, String> paasBusinessTypeToName, Integer formBusinessType) {
        if (formBusinessType != 0
                && Objects.nonNull(paasBusinessTypeToName.get(formBusinessType))
                && !Objects.equals(paasBusinessTypeToName.get(formBusinessType), XbbRefTypeEnum.getByCode(formBusinessType).getName())) {
            tabConfigPojo.setName(paasBusinessTypeToName.get(formBusinessType));
        }
    }


    /**
     * 去除无权限或者已被删除的关联列表
     * @param tabConfigPojos tab 列表
     * @param detailTabMap 关联列表的tab
     */
    public void deleteLinkList(List<TabConfigPojo> tabConfigPojos, Map<String, DetailTabPojo> detailTabMap) {
        Iterator<TabConfigPojo> iterator = tabConfigPojos.iterator();
        // 遍历tab，如果是关联列表，并且关联列表的tab中没有这个了，则需要将其从tab中删除，可能是表单被删除了或者没权限了
        while (iterator.hasNext()) {
            TabConfigPojo tabConfigPojo = iterator.next();
            if (Objects.equals(DetailTabEnum.LINK_LIST.getKey(), tabConfigPojo.getKey())
                    && !detailTabMap.containsKey(tabConfigPojo.getAttr())) {
                iterator.remove();
                continue;
            }
            if (detailTabMap.containsKey(tabConfigPojo.getAttr())) {
                tabConfigPojo.setName(detailTabMap.get(tabConfigPojo.getAttr()).getName());
            }
        }
    }

    /**
     * 设置关联列表
     * @param tabConfigPojos
     * @param detailTabMap
     * @param configPojoMap
     * @param sort
     */
    public void setLastLinkListSort(List<TabConfigPojo> tabConfigPojos, Map<String, DetailTabPojo> detailTabMap, Map<String, TabConfigPojo> configPojoMap, Integer sort) {


        for (Map.Entry<String, DetailTabPojo> entry : detailTabMap.entrySet()) {
            if (!configPojoMap.containsKey(entry.getKey()) || configPojoMap.isEmpty()) {
                TabConfigPojo tabConfigPojo = new TabConfigPojo();
                tabConfigPojo.setAttr(entry.getKey());
                tabConfigPojo.setName(entry.getValue().getName());
                tabConfigPojo.setKey(entry.getValue().getKey());
                tabConfigPojo.setSort(sort++);
                tabConfigPojo.setEnable(BasicConstant.IS_USE);
                tabConfigPojos.add(tabConfigPojo);
            }
        }
    }

    public void setLastAddSubFormSort(List<TabConfigPojo> tabConfigPojos, Map<String, FieldAttrEntity> subFormMap, Map<String, TabConfigPojo> configPojoMap, Integer sort) {
        TabConfigPojo tabConfigPojo;
        for (Map.Entry<String, FieldAttrEntity> entry : subFormMap.entrySet()) {
            if (!configPojoMap.containsKey(entry.getKey())) {
                tabConfigPojo = new TabConfigPojo();
                tabConfigPojo.setAttr(entry.getKey());
                tabConfigPojo.setName(entry.getValue().getAttrName());
                tabConfigPojo.setKey(FieldTypeEnum.SUB_FORM.getEsalias());
                tabConfigPojo.setSort(sort++);
                tabConfigPojo.setEnable(BasicConstant.IS_USE);
                tabConfigPojos.add(tabConfigPojo);
            }
        }
    }

    public void setSubFormTabSort(List<TabConfigPojo> tabConfigPojos, Map<String, FieldAttrEntity> subFormMap, Integer sort, List<Object> pojoList) {
        TabConfigPojo tabConfigPojo;
        for (Map.Entry<String, FieldAttrEntity> entry : subFormMap.entrySet()) {
            tabConfigPojo = new TabConfigPojo();
            tabConfigPojo.setAttr(entry.getKey());
            tabConfigPojo.setName(entry.getValue().getAttrName());
            tabConfigPojo.setKey(FieldTypeEnum.SUB_FORM.getEsalias());
            tabConfigPojo.setSort(sort++);
            tabConfigPojo.setEnable(BasicConstant.IS_USE);
            tabConfigPojos.add(tabConfigPojo);
        }
        for (Object obj : pojoList) {
            tabConfigPojo = getTabConfig(obj);
            tabConfigPojo.setSort(sort++);
            tabConfigPojos.add(tabConfigPojo);
        }
    }

    protected TabConfigPojo getTabConfig(Object obj) {
        TabConfigPojo tabConfigPojo;
        if(obj instanceof BusinessDetailTabEnum){
            BusinessDetailTabEnum tabEnum = (BusinessDetailTabEnum)obj;
            tabConfigPojo = new TabConfigPojo();
            BeanUtil.copyProperties(tabEnum.getAnEnum(), tabConfigPojo);
            tabConfigPojo.setAttr(tabEnum.getAnEnum().getKey());
            tabConfigPojo.setEnable(BasicConstant.IS_USE);

            tabConfigPojo.setSpecialMemo(tabEnum.getSpecialMemo());

        }else{
            PaasDetailTabEnum tabEnum = (PaasDetailTabEnum)obj;
            tabConfigPojo = new TabConfigPojo();
            BeanUtil.copyProperties(tabEnum.getAnEnum(), tabConfigPojo);
            tabConfigPojo.setAttr(tabEnum.getAnEnum().getKey());
            tabConfigPojo.setEnable(BasicConstant.IS_USE);
        }
        return tabConfigPojo;
    }

    /**
     * 设置客户上下级tab的显隐
     *
     * @param detailTabSettingGetDTO
     * @param explainList
     * @throws
     * @author long.rao
     * @date 2020-06-11 15:12
     */
    private boolean setParentCustomerShow(DetailTabSettingGetDTO detailTabSettingGetDTO, List<FieldAttrEntity> explainList) throws XbbException{
        boolean parentCustomerShow = true;
        Long dataId = detailTabSettingGetDTO.getDataId();
        String corpid = detailTabSettingGetDTO.getCorpid();
        if (Objects.isNull(dataId)) {
            return parentCustomerShow;
        }
        CustomerEntityExt customerEntityExt = customerModel.getByKey(dataId, corpid);
        if (Objects.nonNull(customerEntityExt)) {
            String creatorId = FastJsonHelper.getStringOrDefaultFromFormData(customerEntityExt.getData(), CustomerManagementEnum.CREATOR.getAttr(), "");
            //协同团队
            Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            formDataFormExplainHelper.getUserIdMap(Collections.singletonList(dataId),corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),false,mainUserMap,coUserMap);

            // 当前数据的创建人、负责人、协同人、当前操作人
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            handlerExplainDTO.setLoginUser(detailTabSettingGetDTO.getLoginUser());
            handlerExplainDTO.setUserId(detailTabSettingGetDTO.getUserId());
            handlerExplainDTO.setOwnerId(mainUserMap.get(dataId));
            handlerExplainDTO.setCoUserId(coUserMap.get(dataId));
            handlerExplainDTO.setCreatorId(creatorId);
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
            explainList.forEach(item -> explainMap.put(item.getAttr(), item));
            parentCustomerShow = commonHelp.attrCanSee(CustomerManagementEnum.PARENT.getAttr(), explainMap, handlerExplainDTO);
        }
        return parentCustomerShow;
    }

}
